const cacheKey = {
  //辅助
  expiredTime: 'EXPIRED:TIME',
  expiredStartTime: 'EXPIRED:START:TIME',
  //全局使用
  //用户信息
  loginUserInfo: 'USER:INFO',
  //搜索字段
  searchString: 'SEARCH:STRING',
  searchType: 'SEARCH:TYPR'
};
/**
 * 设置缓存
 *
 * @param key
 * @param value
 * @param expiredTimeMS  过期时间，单位ms
 */
let cacheSet = function (key: string, value: any, expiredTimeMS: number) {
  console.log(`cache set: key=${key} value = ${value} expiredTimeMS = ${expiredTimeMS}`);
  if (expiredTimeMS == 0 || expiredTimeMS == null) {
    localStorage.setItem(key, value);
  } else {
    localStorage.setItem(key, JSON.stringify(value));
    localStorage.setItem(key + cacheKey.expiredTime, `${expiredTimeMS}`);
    localStorage.setItem(key + cacheKey.expiredStartTime, `${new Date().getTime()}`);
  }
};
/**
 *  获取键
 *
 * @param key
 * @returns {*} key存在，返回对象；不存在，返回null
 */
let cacheGet = function (key: string) {
  var expiredTimeMS = localStorage.getItem(key + cacheKey.expiredTime);
  var expiredStartTime = localStorage.getItem(key + cacheKey.expiredStartTime);
  var curTime = new Date().getTime();

  var sum = Number(expiredStartTime) + Number(expiredTimeMS);

  if (sum > curTime) {
    console.log(`cache-缓存[${key}]存在！`);
    const cacheStr = localStorage.getItem(key) || '';
    return JSON.parse(cacheStr);
  } else {
    console.log(`cache-缓存[${key}]不存在！`);
    cacheRemove(key);
    return null;
  }
};
/**
 *  移除键
 *
 * @param key
 */
let cacheRemove = function (key: string) {
  localStorage.removeItem(key);
  localStorage.removeItem(key + cacheKey.expiredTime);
  localStorage.removeItem(key + cacheKey.expiredStartTime);
};
/**
 * 对键重新更新过期时间
 *
 * @param key
 * @param expiredTimeMS  过期时间ms
 */
let cacheExpired = function (key: string, expiredTimeMS: number) {
  if (cacheGet(key) != null) {
    localStorage.setItem(key + cacheKey.expiredTime, `${expiredTimeMS}`);
  }
};
/**
 * 清除所有缓存
 */
let cacheClear = function () {
  localStorage.clear();
};

export { cacheSet, cacheGet, cacheRemove, cacheExpired, cacheClear };
